/* Andreas Baum
 * JBPServerConnector.java
 * Handles setting up the server proxy
 * CS 78 - Networks
 */

/* 
 * The notion of "server" in this project can lead to confusion: 
 * Indeed, it is employed with two separate meanings.
 * 1. The central login server
 * 2. The "server" side of the iTunes connection to which another proxy connect
 * , and which allows another user to access the user's iTunes library.
 */

package jbpServerConnector;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import jbpClientConnector.DataThread;
import jbpClientConnector.JBPClientConnector;

public class JBPServerConnector extends Thread {

	public static int SERVER_PORT = JBPClientConnector.SERVER_PORT;
	public static int ITUNES_PORT = 3689;
	public static ServerSocket extSocket;

	public JBPServerConnector() throws IOException {
		this.start();
	}

	public void run() {
		// Declare the external proxy thread:
		DataThread sExtThread;

		
		// The proxy server connects directly to iTunes on the DAAP port 3689:  
		Socket iTunesSocket = null;
		try {
			iTunesSocket = new Socket("localhost", ITUNES_PORT);
		} catch (UnknownHostException e1) {
			// TODO Auto-generated catch block
			System.err.println("Unknown host: localhost.");
			e1.printStackTrace();
			System.exit(1);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.exit(1);
		}
		// Create a DataThread to handle the communication with iTunes:
		DataThread iTunesDataThread = new DataThread(iTunesSocket, "iTunesDataThread");


		// The proxy server listens on SERVER_PORT for the client connection:
		// Bind to port:
		try {
			extSocket = new ServerSocket(SERVER_PORT);
		} catch (IOException e) {
			System.err.println("JBPServerConnector error: Could not listen on port: " + SERVER_PORT);
			System.err.println("Verify that the server isn't already running.");
			System.exit(-1);
		}

		// listen for a new connection and
		// create a client thread to handle the client:
		while(true){
			try {
				new ServerThreadPair(extSocket.accept());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.exit(1);
			}
		}
	}

}